/**
 * @Creator: eyes
 * @Date: 2019/12/23
 * 用户按省市分布的统计表格
 */

import React, {useContext} from 'react';
import {Table} from 'antd';
import {StoreContext} from '../data';

// 用于渲染省份表格下嵌套的城市子表格
const renderNestedCities = ({cities}) => {

    const columns
    = [
        ['城市', 'city', 'city_c'],
        ['人次', 'pv', 'pv_c'],
        ['占比', 'percent', 'percent_c']
    ].map(([title, dataIndex, key]) => ({
        title,
        dataIndex,
        key,
        width: 300,
        align: 'center',
        ellipsis: true,
    }));

    const data = cities.map(({city, pv, percent}, index) => ({
        city,
        pv,
        percent: `${percent}%`,
        key: `keyChild${index}`

    }));

    return (
        <Table
            columns={columns}
            dataSource={data}
            pagination={false}
        />
    );
};

export default () => {
    // 数据结构:[{province, pv, percent, userCityPvs: [{city, pv, percent}]}]
    const {
        state: {
            areaSearchResult,
            selectedAreaMapProvince,
            areaSearchLoading,
        },
    } = useContext(StoreContext);

    const columns
        =  [
            ['省份', 'province', 'province_p'],
            ['人次', 'pv', 'pv_p'],
            ['占比', 'percent', 'percent_p']
        ].map(([title, dataIndex, key]) => ({
            title,
            dataIndex,
            key,
            width: 300,
            align: 'left',
            ellipsis: true,
        }));

    // 根据用户在地图中点击选中的省份, 在表格中进行过滤展示
    const showProvinces = selectedAreaMapProvince.length
        ? areaSearchResult.filter(_ => selectedAreaMapProvince.includes(_.province))
        : areaSearchResult;

    const data = showProvinces.map(({province, pv, percent, userCityPvs}, index) => ({
        province,
        pv,
        percent: `${percent}%`,
        cities: userCityPvs,
        key: `key${index}`
    }));

    return (
        <Table
            className="components-table-demo-nested"
            columns={columns}
            expandedRowRender={renderNestedCities}
            dataSource={data}
            pagination={false}
            loading={areaSearchLoading}
        />
    );
};
